package com.smcdd.cdb.dbo.cdb_dbo.ui.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.smcdd.cdb.dbo.cdb_dbo.R;
import com.smcdd.cdb.dbo.cdb_dbo.app.App;
import com.smcdd.cdb.dbo.cdb_dbo.network.HttpObserver;
import com.smcdd.cdb.dbo.cdb_dbo.network.factory.RetrofitFactory;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.LocationBean;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.StoreInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.NetWorkCodeInfo;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.DemoUtils;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.DialogUtils;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainEncry;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainVersion;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ToastUtil;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.tencent.map.geolocation.TencentPoi;
import com.tencent.mapsdk.raster.model.BitmapDescriptorFactory;
import com.tencent.mapsdk.raster.model.LatLng;
import com.tencent.mapsdk.raster.model.Marker;
import com.tencent.mapsdk.raster.model.MarkerOptions;
import com.tencent.tencentmap.mapsdk.map.MapActivity;
import com.tencent.tencentmap.mapsdk.map.MapView;
import com.tencent.tencentmap.mapsdk.map.TencentMap;
import com.tencent.tencentmap.mapsdk.map.UiSettings;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 作者：Administrator on 2017/10/24 17:32
 * 邮箱：zhanghuaiha@gmail.com
 */

public class ShopMapActivity extends MapActivity implements TencentLocationListener {

    private MapView mapview;
    private TencentMap map;
    private int mLevel = 2;
    private TencentLocationManager mLocationManager;
    private ImageView map_back;
    private TextView map_save;
    private Marker marker;
    private static final int LAT_LOG = 5;// 经纬度
    private Dialog dialog;
    private String udid;
    private String eid;
    private String versionName;
    private EditText map_search;
    private double log,lat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopmap);

        mapview = (MapView) findViewById(R.id.mapview);
        map_back = (ImageView) findViewById(R.id.map_back);
        map_save = (TextView) findViewById(R.id.map_save);
        map_search = (EditText) findViewById(R.id.map_search);
        map_back.setOnClickListener(v -> finish());
        udid = App.SP.getString("udid", "");
        eid = App.SP.getString("id", "");
        versionName = ObtainVersion.getVersionName(this);
        //搜索
        map_save.setOnClickListener(v -> {
            map.clearAllOverlays();
            String name = map_search.getText().toString();
            search(name);
        });


        if (Build.VERSION.SDK_INT >= 23) {
            String[] permissions = {
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            };
            if(checkSelfPermission(permissions[0]) == PackageManager.PERMISSION_DENIED){
                requestPermissions(permissions, 0);
            }
        }

        mLocationManager = TencentLocationManager.getInstance(this);
        // 设置坐标系为 gcj-02, 缺省坐标为 gcj-02, 所以通常不必进行如下调用
        // mLocationManager.setCoordinateType(TencentLocationManager.COORDINATE_TYPE_GCJ02);
        startLocation();
    }

    private void ininData(LocationBean locationBean) {
        map = mapview.getMap();
        map.setCenter(new LatLng(locationBean.getLat(),locationBean.getLog()));
        map.setZoom(15);
        lat = locationBean.getLat();
        log = locationBean.getLog();

        //获取UiSettings实例
        UiSettings uiSettings = mapview.getUiSettings();
        //设置logo到屏幕底部中心
        uiSettings.setLogoPosition(UiSettings.LOGO_POSITION_CENTER_BOTTOM);
        //设置比例尺到屏幕右下角
        uiSettings.setScaleViewPosition(UiSettings.SCALEVIEW_POSITION_RIGHT_BOTTOM);

        marker = mapview.addMarker(new MarkerOptions()
                .position(new LatLng(locationBean.getLat(),locationBean.getLog()))
                .title("长按拖动图标选择位置")
                .anchor(0.5f, 0.5f)
                .draggable(false) //不允许拖拽
                .icon(BitmapDescriptorFactory
                        .defaultMarker())
                .draggable(true));
        marker.showInfoWindow();// 设置默认显示一个infoWindow

        LatLng position = marker.getPosition();
        Log.e("logcation","维度："+position.getLatitude()+"!!精度："+position.getLongitude());
        LoadData(position.getLatitude(),position.getLongitude());
    }

    private void LoadData(Double lat,Double log) {
        TSDialog();
        String tiem = System.currentTimeMillis() + "";
        Map<String, String> map = new LinkedHashMap<>();
        map.put("rf", "2");
        map.put("ts", tiem);
        map.put("v", versionName);
        map.put("i", NetWorkCodeInfo.STORE);
        map.put("udid", udid);
        map.put("eid", eid);
        map.put("status", "1");
        map.put("latitude", lat+"");
        map.put("longitude", log+"");
        map.put("page_size", "20");
        map.put("page_index", "0");
        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry", encry1);
        RetrofitFactory.getmInstanse().mApi.getStoreInfo(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<StoreInfo>() {
                    @Override
                    public void success(StoreInfo storeInfo) {
                        if (storeInfo.getCode() == 200) {
                            for (int i = 0; i < storeInfo.getData().size(); i++) {
                                if ("1".equals(storeInfo.getData().get(i).getStore_type())) {
                                    //wifi
                                    Marker marker = mapview.addMarker(new MarkerOptions()
                                            .position(new LatLng( Double.parseDouble(storeInfo.getData().get(i).getLatitude()), Double.parseDouble(storeInfo.getData().get(i).getLongitude())))
                                            .anchor(0.5f, 0.5f)
                                            .title(storeInfo.getData().get(i).getName())
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.wifi_blue))
                                            .draggable(true));
                                    marker.showInfoWindow();// 设置默认显示一个infoWindow
                                    marker.hideInfoWindow();
                                }else if ("4".equals(storeInfo.getData().get(i).getStore_type())) {
                                    //密码
                                    Marker marker = mapview.addMarker(new MarkerOptions()
                                            .position(new LatLng( Double.parseDouble(storeInfo.getData().get(i).getLatitude()), Double.parseDouble(storeInfo.getData().get(i).getLongitude())))
                                            .anchor(0.5f, 0.5f)
                                            .title(storeInfo.getData().get(i).getName())
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.mima_blue))
                                            .draggable(true));
                                    marker.showInfoWindow();// 设置默认显示一个infoWindow
                                    marker.hideInfoWindow();
                                }else if ("5".equals(storeInfo.getData().get(i).getStore_type())){
                                    //纸巾机
                                    Marker marker = mapview.addMarker(new MarkerOptions()
                                            .position(new LatLng( Double.parseDouble(storeInfo.getData().get(i).getLatitude()), Double.parseDouble(storeInfo.getData().get(i).getLongitude())))
                                            .anchor(0.5f, 0.5f)
                                            .title(storeInfo.getData().get(i).getName())
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.zhi_blue))
                                            .draggable(true));
                                    marker.showInfoWindow();// 设置默认显示一个infoWindow
                                    marker.hideInfoWindow();
                                }else if ("11".equals(storeInfo.getData().get(i).getStore_type())) {
                                    //WiFi + 密码
                                    Marker marker = mapview.addMarker(new MarkerOptions()
                                            .position(new LatLng( Double.parseDouble(storeInfo.getData().get(i).getLatitude()), Double.parseDouble(storeInfo.getData().get(i).getLongitude())))
                                            .anchor(0.5f, 0.5f)
                                            .title(storeInfo.getData().get(i).getName())
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.mw_blue))
                                            .draggable(true));
                                    marker.showInfoWindow();// 设置默认显示一个infoWindow
                                    marker.hideInfoWindow();
                                }else if ("12".equals(storeInfo.getData().get(i).getStore_type())) {
                                    //WiFi + 纸巾机
                                    Marker marker = mapview.addMarker(new MarkerOptions()
                                            .position(new LatLng( Double.parseDouble(storeInfo.getData().get(i).getLatitude()), Double.parseDouble(storeInfo.getData().get(i).getLongitude())))
                                            .anchor(0.5f, 0.5f)
                                            .title(storeInfo.getData().get(i).getName())
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.zw_blue))
                                            .draggable(true));
                                    marker.showInfoWindow();// 设置默认显示一个infoWindow
                                    marker.hideInfoWindow();
                                }else if ("13".equals(storeInfo.getData().get(i).getStore_type())) {
                                    //密码 + 纸巾机
                                    Marker marker = mapview.addMarker(new MarkerOptions()
                                            .position(new LatLng( Double.parseDouble(storeInfo.getData().get(i).getLatitude()), Double.parseDouble(storeInfo.getData().get(i).getLongitude())))
                                            .anchor(0.5f, 0.5f)
                                            .title(storeInfo.getData().get(i).getName())
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.mz_blue))
                                            .draggable(true));
                                    marker.showInfoWindow();// 设置默认显示一个infoWindow
                                    marker.hideInfoWindow();
                                }else if ("14".equals(storeInfo.getData().get(i).getStore_type())) {
                                    //WiFi + 密码 + 纸巾机
                                    Marker marker = mapview.addMarker(new MarkerOptions()
                                            .position(new LatLng( Double.parseDouble(storeInfo.getData().get(i).getLatitude()), Double.parseDouble(storeInfo.getData().get(i).getLongitude())))
                                            .anchor(0.5f, 0.5f)
                                            .title(storeInfo.getData().get(i).getName())
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.wmz_blue))
                                            .draggable(true));
                                    marker.showInfoWindow();// 设置默认显示一个infoWindow
                                    marker.hideInfoWindow();
                                }else {
                                    //待铺设
                                    Marker marker = mapview.addMarker(new MarkerOptions()
                                            .position(new LatLng( Double.parseDouble(storeInfo.getData().get(i).getLatitude()), Double.parseDouble(storeInfo.getData().get(i).getLongitude())))
                                            .anchor(0.5f, 0.5f)
                                            .title(storeInfo.getData().get(i).getName())
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.mipmap.weipushe))
                                            .draggable(true));
                                    marker.showInfoWindow();// 设置默认显示一个infoWindow
                                    marker.hideInfoWindow();
                                }
                            }
                        }
                        dialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        dialog.dismiss();
                    }
                });


    }
    public void TSDialog() {
        dialog = DialogUtils.uploadDialog(this, getString(R.string.upload), true);
    }
    //搜索
    public void search(String name) {
        TSDialog();
        String tiem = System.currentTimeMillis() + "";
        Map<String, String> map = new LinkedHashMap<>();
        map.put("rf", "2");
        map.put("ts", tiem);
        map.put("v", versionName);
        map.put("i", NetWorkCodeInfo.STORE);
        map.put("udid", udid);
        map.put("eid", eid);
        map.put("status", "1");
        map.put("page_size", "20");
        map.put("page_index","0");
        map.put("name", name);
        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry", encry1);
        RetrofitFactory.getmInstanse().mApi.getStoreInfo(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<StoreInfo>() {
                    @Override
                    public void success(StoreInfo storeInfo) {
                        if (storeInfo.getCode() == 200 && storeInfo.getData().size() > 0) {
                            marker = mapview.addMarker(new MarkerOptions()
                                    .position(new LatLng(lat,log))
                                    .title("长按拖动图标选择位置")
                                    .anchor(0.5f, 0.5f)
                                    .draggable(false) //不允许拖拽
                                    .icon(BitmapDescriptorFactory
                                            .defaultMarker())
                                    .draggable(true));
                            marker.showInfoWindow();// 设置默认显示一个infoWindow

                            for (int i = 0; i < storeInfo.getData().size(); i++) {
                                if ("1".equals(storeInfo.getData().get(i).getStore_type())) {
                                    //wifi
                                    Marker marker = mapview.addMarker(new MarkerOptions()
                                            .position(new LatLng( Double.parseDouble(storeInfo.getData().get(i).getLatitude()), Double.parseDouble(storeInfo.getData().get(i).getLongitude())))
                                            .anchor(0.5f, 0.5f)
                                            .title(storeInfo.getData().get(i).getName())
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.wifi_blue))
                                            .draggable(true));
                                    marker.showInfoWindow();// 设置默认显示一个infoWindow
                                    marker.hideInfoWindow();
                                }else if ("4".equals(storeInfo.getData().get(i).getStore_type())) {
                                    //密码
                                    Marker marker = mapview.addMarker(new MarkerOptions()
                                            .position(new LatLng( Double.parseDouble(storeInfo.getData().get(i).getLatitude()), Double.parseDouble(storeInfo.getData().get(i).getLongitude())))
                                            .anchor(0.5f, 0.5f)
                                            .title(storeInfo.getData().get(i).getName())
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.mima_blue))
                                            .draggable(true));
                                    marker.showInfoWindow();// 设置默认显示一个infoWindow
                                    marker.hideInfoWindow();
                                }else if ("5".equals(storeInfo.getData().get(i).getStore_type())){
                                    //纸巾机
                                    Marker marker = mapview.addMarker(new MarkerOptions()
                                            .position(new LatLng( Double.parseDouble(storeInfo.getData().get(i).getLatitude()), Double.parseDouble(storeInfo.getData().get(i).getLongitude())))
                                            .anchor(0.5f, 0.5f)
                                            .title(storeInfo.getData().get(i).getName())
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.zhi_blue))
                                            .draggable(true));
                                    marker.showInfoWindow();// 设置默认显示一个infoWindow
                                    marker.hideInfoWindow();
                                }else if ("11".equals(storeInfo.getData().get(i).getStore_type())) {
                                    //WiFi + 密码
                                    Marker marker = mapview.addMarker(new MarkerOptions()
                                            .position(new LatLng( Double.parseDouble(storeInfo.getData().get(i).getLatitude()), Double.parseDouble(storeInfo.getData().get(i).getLongitude())))
                                            .anchor(0.5f, 0.5f)
                                            .title(storeInfo.getData().get(i).getName())
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.mw_blue))
                                            .draggable(true));
                                    marker.showInfoWindow();// 设置默认显示一个infoWindow
                                    marker.hideInfoWindow();
                                }else if ("12".equals(storeInfo.getData().get(i).getStore_type())) {
                                    //WiFi + 纸巾机
                                    Marker marker = mapview.addMarker(new MarkerOptions()
                                            .position(new LatLng( Double.parseDouble(storeInfo.getData().get(i).getLatitude()), Double.parseDouble(storeInfo.getData().get(i).getLongitude())))
                                            .anchor(0.5f, 0.5f)
                                            .title(storeInfo.getData().get(i).getName())
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.zw_blue))
                                            .draggable(true));
                                    marker.showInfoWindow();// 设置默认显示一个infoWindow
                                    marker.hideInfoWindow();
                                }else if ("13".equals(storeInfo.getData().get(i).getStore_type())) {
                                    //密码 + 纸巾机
                                    Marker marker = mapview.addMarker(new MarkerOptions()
                                            .position(new LatLng( Double.parseDouble(storeInfo.getData().get(i).getLatitude()), Double.parseDouble(storeInfo.getData().get(i).getLongitude())))
                                            .anchor(0.5f, 0.5f)
                                            .title(storeInfo.getData().get(i).getName())
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.mz_blue))
                                            .draggable(true));
                                    marker.showInfoWindow();// 设置默认显示一个infoWindow
                                    marker.hideInfoWindow();
                                }else if ("14".equals(storeInfo.getData().get(i).getStore_type())) {
                                    //WiFi + 密码 + 纸巾机
                                    Marker marker = mapview.addMarker(new MarkerOptions()
                                            .position(new LatLng( Double.parseDouble(storeInfo.getData().get(i).getLatitude()), Double.parseDouble(storeInfo.getData().get(i).getLongitude())))
                                            .anchor(0.5f, 0.5f)
                                            .title(storeInfo.getData().get(i).getName())
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.wmz_blue))
                                            .draggable(true));
                                    marker.showInfoWindow();// 设置默认显示一个infoWindow
                                    marker.hideInfoWindow();
                                }else {
                                    //待铺设
                                    Marker marker = mapview.addMarker(new MarkerOptions()
                                            .position(new LatLng( Double.parseDouble(storeInfo.getData().get(i).getLatitude()), Double.parseDouble(storeInfo.getData().get(i).getLongitude())))
                                            .anchor(0.5f, 0.5f)
                                            .title(storeInfo.getData().get(i).getName())
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.mipmap.weipushe))
                                            .draggable(true));
                                    marker.showInfoWindow();// 设置默认显示一个infoWindow
                                    marker.hideInfoWindow();
                                }
                            }
                        }else {
                            ToastUtil.showToast("未发现该店铺信息");
                        }
                        dialog.dismiss();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        dialog.dismiss();
                    }
                });
    }


    // 响应点击"开始"
    public void startLocation() {
        // 创建定位请求
        TencentLocationRequest request = TencentLocationRequest.create()
                .setInterval(5000) // 设置定位周期
                .setAllowGPS(true)  //当为false时，设置不启动GPS。默认启动
                .setAllowIndoorLocation(true)  //设置启动室内定位，默认不启动
                .setQQ("10001")
                .setRequestLevel(TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA); // 设置定位level

        // 开始定位
        mLocationManager.requestLocationUpdates(request, this);

        Log.e("mappp", DemoUtils.toString(mLocationManager.getCoordinateType()));
    }

    @Override
    protected void onStop() {
        super.onStop();
        mLocationManager.removeUpdates(this);
    }



    @Override
    public void onLocationChanged(TencentLocation location, int error, String s) {
        LocationBean locationBean = null;
        if (error == TencentLocation.ERROR_OK) {
            // 定位成功
            locationBean = toString(location, TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA);
        } else {
            // 定位失败
            String msg = "定位失败: " + s;
            locationBean = new LocationBean();
            locationBean.setName(msg);
        }
        updateLocationStatus(locationBean);
    }

    @Override
    public void onStatusUpdate(String s, int i, String s1) {

    }

    // ====== location callback

    private void updateLocationStatus(LocationBean locationBean) {
        mLocationManager.removeUpdates(this);
        ininData(locationBean);
        Log.e("map",locationBean.getName());

    }


    // ===== util method
    private static LocationBean toString(TencentLocation location, int level) {
        StringBuilder sb = new StringBuilder();
        if (location.getLatitude() != 0.0 && location.getLongitude() != 0.0) {
            LocationBean locationBean = new LocationBean();
            locationBean.setLat(location.getLatitude());
            locationBean.setLog(location.getLongitude());
            locationBean.setName("获取定位成功");
            return locationBean;
        }

        sb.append("latitude=").append(location.getLatitude()).append(",");
        sb.append("longitude=").append(location.getLongitude()).append(",");
        sb.append("altitude=").append(location.getAltitude()).append(",");
        sb.append("accuracy=").append(location.getAccuracy()).append(",");
        sb.append("indoorBuildingId=").append(location.getIndoorBuildingId()).append(",");
        sb.append("indoorBuildingFloor=").append(location.getIndoorBuildingFloor()).append(",");

        switch (level) {
            case TencentLocationRequest.REQUEST_LEVEL_GEO:
                break;

            case TencentLocationRequest.REQUEST_LEVEL_NAME:
                sb.append("name=").append(location.getName()).append(",");
                sb.append("address=").append(location.getAddress()).append(",");
                break;

            case TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA:
            case TencentLocationRequest.REQUEST_LEVEL_POI:
            case 7:
                sb.append("nation=").append(location.getNation()).append(",");
                sb.append("province=").append(location.getProvince()).append(",");
                sb.append("city=").append(location.getCity()).append(",");
                sb.append("district=").append(location.getDistrict()).append(",");
                sb.append("town=").append(location.getTown()).append(",");
                sb.append("village=").append(location.getVillage()).append(",");
                sb.append("street=").append(location.getStreet()).append(",");
                sb.append("streetNo=").append(location.getStreetNo()).append(",");

                if (level == TencentLocationRequest.REQUEST_LEVEL_POI) {
                    List<TencentPoi> poiList = location.getPoiList();
                    int size = poiList.size();
                    for (int i = 0, limit = 3; i < limit && i < size; i++) {
                        sb.append("\n");
                        sb.append("poi[" + i + "]=")
                                .append(toString(poiList.get(i))).append(",");
                    }
                }

                break;

            default:
                break;
        }

        return null;
    }

    private static String toString(TencentPoi poi) {
        StringBuilder sb = new StringBuilder();
        sb.append("name=").append(poi.getName()).append(",");
        sb.append("address=").append(poi.getAddress()).append(",");
        sb.append("catalog=").append(poi.getCatalog()).append(",");
        sb.append("distance=").append(poi.getDistance()).append(",");
        sb.append("latitude=").append(poi.getLatitude()).append(",");
        sb.append("longitude=").append(poi.getLongitude()).append(",");
        return sb.toString();
    }
}
